<template>
  <el-card class="main-card">
    <!-- 基础信息部分 -->
    <div class="base-info">
      <el-form :model="form" label-width="120px" class="form-container">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划主题">
              <el-input
                v-model="form.planTheme"
                placeholder="请输入计划主题"
                class="input-style"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划单号">
              <el-input
                v-model="form.planNumber"
                placeholder="系统自动生成"
                class="input-style"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单据日期">
              <el-date-picker
                v-model="form.billDate"
                type="date"
                placeholder="选择日期"
                class="input-style"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联项目">
              <el-select
                v-model="form.relatedProject"
                placeholder="请选择关联项目"
                class="input-style"
                filterable
              >
                <el-option
                  label="A项目-智能硬件"
                  value="A项目-智能硬件"
                ></el-option>
                <el-option
                  label="B项目-工业软件"
                  value="B项目-工业软件"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="请输入备注信息"
            class="textarea-style"
            :rows="3"
          ></el-input>
        </el-form-item>

        <el-form-item label="销售订单">
          <el-input
            v-model="form.salesOrder"
            placeholder="请输入销售订单号"
            class="input-style"
            :disabled="form.unbindSalesOrder"
          ></el-input>
          <el-checkbox v-model="form.unbindSalesOrder" class="checkbox-style"
            >不绑定销售订单</el-checkbox
          >
        </el-form-item>
      </el-form>
    </div>

    <!-- 生产物品部分 -->
    <div class="production-section">
      <div class="table-actions">
        <el-button
          type="primary"
          size="small"
          @click="openProductSelector"
          class="action-btn"
        >
          <i class="el-icon-circle-plus"></i> 添加
        </el-button>
        <el-button
          type="danger"
          size="small"
          @click="removeSelectedItems"
          class="action-btn"
        >
          <i class="el-icon-circle-remove"></i> 移除
        </el-button>
      </div>

      <el-table
        :data="dialogProductList"
        border
        style="width: 100%"
        class="custom-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" type="index" width="60"></el-table-column>
        <el-table-column
          prop="materialCode"
          label="物品编号"
          width="220"
        ></el-table-column>
        <el-table-column
          prop="materialName"
          label="物品名称"
          width="250"
        ></el-table-column>
        <el-table-column
          prop="modelSpec"
          label="规格型号"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="mainUnit"
          label="单位"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="businessType"
          label="物品类别"
          width="150"
        ></el-table-column>
        <el-table-column prop="detailsDate" width="140px" label="需求日期">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.detailsDate"
              type="date"
              placeholder="需求日期"
              value-format="YYYY-MM-DD"
              class="demand-date-picker"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="130">
          <template #default="scope">
            <el-input
              placeholder="请输入数量"
              v-model="scope.row.demandquantity"
              size="small"
              type="number"
              class="input-style"
              @input="calculateTotal"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="180">
          <template #default="scope">
            <el-input
              placeholder="请输入备注"
              v-model="scope.row.remark"
              size="small"
              class="input-style"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button
              size="small"
              type="text"
              @click="removeItem(scope.row)"
              class="text-btn"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="total-info">
        <span class="total-label">合计：</span>
        <span class="total-value">总量: {{ totalQuantity }} 个</span>
      </div>
    </div>

    <!-- 附件部分 -->
    <div class="attachment-section">
      <div class="section-title">上传附件</div>
      <div class="attachment-list">
        <el-card
          v-for="(attachment, index) in attachments"
          :key="index"
          class="attachment-card"
        >
          <div class="attachment-info">
            <i class="el-icon-document"></i>
            <span class="file-name">{{ attachment.name }}</span>
            <span class="file-size">{{ attachment.size }}MB</span>
            <span class="file-date">{{ attachment.uploadDate }}</span>
          </div>
          <div class="attachment-actions">
            <el-button
              size="small"
              type="text"
              @click="reUpload(attachment)"
              class="text-btn"
              >重新上传</el-button
            >
            <el-button
              size="small"
              type="text"
              @click="deleteAttachment(attachment)"
              class="text-btn"
              >删除</el-button
            >
          </div>
        </el-card>
      </div>

      <!-- 附件上传组件 -->
      <el-upload
        :http-request="customUpload"
        :before-upload="beforeUpload"
        multiple
        class="upload-container"
        drag
      >
        <template #default>
          <i class="el-icon-upload el-icon--large"></i>
          <div class="upload-tip">点击上传或拖拽文件到此处</div>
          <div class="upload-note">支持PDF/Word/Excel，单文件不超过50MB</div>
        </template>
      </el-upload>
    </div>

    <!-- 操作按钮 -->
    <div class="button-group">
      <el-button type="text" @click="close" class="cancel-btn">关闭</el-button>
      <el-button type="primary" @click="confirm" class="submit-btn"
        >确定提交</el-button
      >
    </div>
  </el-card>
  <el-dialog
    title="选择产品"
    ref="dialogRef"
    v-model="dialogVisible"
    width="1200px"
  >
    <div class="search-bar">
      <el-input
        placeholder="请输入分类名称"
        v-model="searchCategory"
        prefix-icon="el-icon-search"
      ></el-input>
      <el-input placeholder="物料编码" v-model="searchCode"></el-input>
      <el-input placeholder="物料名称" v-model="searchName"></el-input>
      <el-button>连选</el-button>
    </div>
    <el-table
      @selection-change="handleSelectionChange"
      :data="materialList"
      border
      style="width: 1800px"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column
        prop="materialCode"
        label="物料编码"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="materialName"
        label="物料名称"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="modelSpec"
        label="型号规格"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="mainUnit"
        label="单位"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="businessType"
        label="物品类别"
        width="200"
      ></el-table-column>
      <el-table-column
        prop="demandquantity"
        label="库存"
        width="200"
      ></el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="form1.PageIndex"
      v-model:page-size="form1.PageSize"
      :page-sizes="[1, 3, 15, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="form1.TotalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <br />
    <div class="button-group">
      <el-button @click="closeDialog" class="action-button">关闭</el-button>
      <el-button type="primary" @click="confirmSelection" class="action-button"
        >选择</el-button
      >
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, ref, onMounted } from "vue";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";

// 附件数据
const attachments = ref([]);

import { Path } from "path-browserify"; // 如需使用 Path.extname，需安装 path-browserify 库
// 或手动实现扩展名解析：
const getFileExtension = (fileName) => {
  const ext = fileName.split(".").pop().toLowerCase();
  return `.${ext}`;
};
//合计
const totalQuantity = ref(0); // 总数量
const calculateTotal = () => {
  let total = 0;
  dialogProductList.value.forEach((item) => {
    // 转换为数字，处理空值或非数字输入（默认0）
    const quantity = parseFloat(item.demandquantity) || 0;
    total += quantity;
  });
  totalQuantity.value = total; // 更新总数量
};
//删除计算数量
const removeItem = (row) => {
  ElMessageBox.confirm("确定要删除该产品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const index = dialogProductList.value.indexOf(row);
      if (index !== -1) {
        dialogProductList.value.splice(index, 1);
        calculateTotal(); // 新增：删除后触发计算
      }
    })
    .catch(() => {});
};
const customUpload = async (file) => {
  const formData = new FormData();
  formData.append("file", file.file); // 注意：el-upload 的 file 参数是 { file: 真实文件, ... }

  try {
    const response = await axios.post(
      "http://localhost:5202/api/UploadFiles",
      formData,
      {
        headers: { "Content-Type": "multipart/form-data" },
      }
    );
    handleUploadSuccess(response.data, file.file);
  } catch (error) {
    handleUploadError(error, file.file);
  }
};

const allowedExtensions = [".pdf", ".doc", ".docx", ".xls", ".xlsx"];
const maxFileSize = 50 * 1024 * 1024;

const beforeUpload = (file) => {
  if (!file || file.size === 0) {
    ElMessage.error("上传文件不能为空");
    return false;
  }

  const fullExt = getFileExtension(file.name);
  if (!allowedExtensions.includes(fullExt)) {
    ElMessage.error(
      "仅支持以下格式：PDF(.pdf)、Word(.doc/.docx)、Excel(.xls/.xlsx)"
    );
    return false;
  }

  if (file.size > maxFileSize) {
    ElMessage.error(`文件大小不能超过 ${maxFileSize / 1024 / 1024}MB`);
    return false;
  }

  return true;
};

const handleUploadSuccess = (response, file) => {
  attachments.value.push({
    name: file.name,
    size: (file.size / 1024 / 1024).toFixed(2),
    uploadDate: new Date().toLocaleString(),
    fileUrl: response.fileUrl,
  });
};

const handleUploadError = (error, file) => {
  let message = "文件上传失败";
  if (error.response && error.response.data) {
    message = error.response.data.message || message;
  }
  ElMessage.error(message);
};
// 提前定义 dialogProductList
const dialogProductList = ref<any[]>([]);
const dialogSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  dialogSelection.value = val;
};

const confirmSelection = () => {
  const selectedRows = dialogSelection.value;
  if (selectedRows.length === 0) {
    ElMessage.warning("请选择产品");
    return;
  }
  selectedRows.forEach((selectedProduct) => {
    dialogProductList.value.push({
      materialCode: selectedProduct.materialCode,
      materialName: selectedProduct.materialName,
      modelSpec: selectedProduct.modelSpec,
      mainUnit: selectedProduct.mainUnit,
      procurementInstructions: selectedProduct.procurementInstructions,
      businessPerson: selectedProduct.businessPerson,
      billCode: selectedProduct.billCode, // 假设默认数量为1，可根据实际调整
      orderDeliveryDate: selectedProduct.orderDeliveryDate,
      businessType: selectedProduct.businessType,
    });
    if (selectedProduct.salesNumber) {
      form.value.salesOrder = selectedProduct.salesNumber;
    }
  });
  if (selectedRows.length > 0) {
    form.value.materialCode = selectedRows[0].materialCode; // 按实际字段名调整
  }

  closeDialog();
};

const form1 = reactive({
  TotalCount: 0,
  PageCount: 0,
  PageSize: 5,
  PageIndex: 1,
});

// 分页 - 每页数量变化
const handleSizeChange = (newSize: number) => {
  form1.PageSize = newSize;
  searchProducts();
};

// 分页 - 当前页变化
const handleCurrentChange = (newPage: number) => {
  form1.PageIndex = newPage;
  searchProducts();
};

// 对话框可见性
const dialogVisible = ref(false);
const closeDialog = () => {
  dialogVisible.value = false;
  dialogSelection.value = []; // 清空已选
};
// 物料列表数据
const materialList = ref<any[]>([]);
const materialListData = ref<any[]>([]); // 物料清单数据
const supplementaryListData = ref<any[]>([]);
// 打开物料选择对话框
const openProductSelector = async () => {
  dialogVisible.value = true;

  searchProducts();
};

const searchProducts = () => {
  dialogVisible.value = true;
  axios
    .get("http://localhost:5202/api/Log/GetProcurement", {
      params: {
        PageSize: form1.PageSize,
        PageIndex: form1.PageIndex,
      },
    })
    .then((res) => {
      materialList.value = res.data.data.list || [];
      form1.TotalCount = res.data.data.totalCount || 0;
      form1.PageCount = res.data.data.PageCount || 0;
    })
    .catch((error) => {
      console.error("获取产品列表失败", error);
      ElMessage.error("获取物料列表失败，请检查网络或重试");
    });
};
// 删除生产信息表格中的产品
const deleteProduct = (product) => {
  ElMessageBox.confirm("确定要删除该产品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const index = dialogProductList.value.indexOf(product);
      if (index !== -1) {
        dialogProductList.value.splice(index, 1);
      }
    })
    .catch(() => {});
};
const generateTwelveDigitNumber = () => {
  const characters = "0123456789";
  let result = "";
  for (let i = 0; i < 12; i++) {
    // 生成12位数字
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
};
//添加
// 基础信息表单数据
const form = ref({
  planTheme: "",
  planNumber: "", // 模拟自动生成的单号
  billDate: dayjs().format("YYYY-MM-DD"),
  remark: "",
  salesOrder: "",
  unbindSalesOrder: false,
  relatedProject: "",
  materialCode: "",
});
const confirm = async () => {
  // 基础信息校验
  if (!form.value.planTheme) {
    ElMessage.error("计划主题不能为空");
    return;
  }
  if (!form.value.planNumber) {
    ElMessage.error("计划单号不能为空");
    return;
  }
  // 其他必填字段校验（如 billDate 等根据业务需求添加）

  // 整理请求数据
  const requestData = {
    ...form.value,
    Products: dialogProductList.value.map((item) => ({
      // 确保字段与后端 PlanInfoProcuctDtos 匹配
      MaterialCode: item.materialCode,
      MaterialName: item.materialName,
      ModelSpec: item.modelSpec,
      MainUnit: item.mainUnit,
      Demandquantity: item.demandquantity,
      BusinessType: item.businessType,
      DetailsDate: item.detailsDate, // 如有该字段
      Remark: item.remark,
    })),
  };
  console.log(requestData);
  try {
    const response = await axios.post(
      "http://localhost:5027/api/Log/AddProductionPlanInfo",
      requestData
    );
    if (response.data.code == 200) {
      // 假设后端返回的枚举值可识别
      ElMessage.success(response.data.message);
    }
  } catch (error) {
    console.error("请求失败", error);
    ElMessage.error("添加过程中发生错误，请检查网络或重试");
  }
};
onMounted(() => {
  form.value.planNumber = generateTwelveDigitNumber();
});
</script>

<style scoped>
/* 主卡片样式 */
.main-card {
  margin: 20px;
  padding: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  border-radius: 12px;
}
.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}
/* 基础信息表单 */
.form-container {
  max-width: 1200px;
  margin: 0 auto;
}
.input-style {
  border-radius: 6px;
  --el-input-border-color: #e5e7eb;
}
.textarea-style {
  border-radius: 6px;
  --el-input-border-color: #e5e7eb;
}
.checkbox-style {
  margin-left: 15px;
  color: #64748b;
}

/* 生产物品部分 */
.production-section {
  margin: 30px 0;
}
.table-actions {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}
.action-btn {
  border-radius: 6px;
  padding: 8px 16px;
}
.custom-table {
  --el-table-border-color: #f3f4f6;
  --el-table-header-bg-color: #f8fafc;
}
.total-info {
  padding: 15px 20px;
  background: #f8fafc;
  border-top: 1px solid #f3f4f6;
  font-weight: 500;
  color: #334155;
}
.total-label {
  color: #64748b;
  margin-right: 10px;
}

/* 附件部分 */
.attachment-section {
  margin: 30px 0;
}
.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #1e293b;
  margin-bottom: 15px;
}
.attachment-list {
  display: grid;
  gap: 12px;
  margin-bottom: 20px;
}
.attachment-card {
  padding: 15px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1px solid #f3f4f6;
  border-radius: 8px;
  transition: all 0.2s;
}
.attachment-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transform: translateY(-2px);
}
.attachment-info {
  display: flex;
  align-items: center;
  gap: 15px;
  color: #334155;
}
.file-name {
  min-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.file-size {
  color: #64748b;
  min-width: 80px;
}
.file-date {
  color: #94a3b8;
  font-size: 12px;
}
.upload-container {
  border: 2px dashed #e5e7eb;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  background: #f8fafc;
  transition: all 0.2s;
}
.upload-container:hover {
  border-color: #3b82f6;
  background: #eff6ff;
}
.upload-tip {
  font-size: 16px;
  color: #1e293b;
  margin: 10px 0 5px;
}
.upload-note {
  font-size: 14px;
  color: #64748b;
}

/* 按钮组 */
.button-group {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  gap: 15px;
}
.submit-btn {
  padding: 10px 24px;
  border-radius: 6px;
  font-size: 14px;
}
.cancel-btn {
  color: #64748b;
  padding: 10px 24px;
  border-radius: 6px;
  font-size: 14px;
}
.text-btn {
  color: #3b82f6;
  transition: color 0.2s;
}
.text-btn:hover {
  color: #2563eb;
}
</style>
